require(quantmod)

symbols=symbolCollection(group="METALS")

for (sym in symbolCollection(group="INDEX")) {
  #plot(dayOffset(get(sym)), main=sym)
  chartSeries(get(sym), name=sym)
}


ht <- function (TS, n=5) {
  c(head(TS, n=n), tail(TS, n=n))
}

if (priceInfo==TRUE) {
  BLEND <- CSPNBlended(TS, N=2)
  FO <- BLEND[,1]* (BullEngulfing | BearEngulfing)
  FH <- BLEND[,2]* (BullEngulfing | BearEngulfing)
  FL <- BLEND[,3]* (BullEngulfing | BearEngulfing)
  FC <- BLEND[,4]* (BullEngulfing | BearEngulfing)
  result <- cbind(result, FO, FH, FL, FC)
}


# define testparameters
symbols     <- c("URZ")
retrieveDate<- '2006-01-01'  # retrieve older data to allow calculation of MA prior to start of trading
initDate    <- '2007-01-01'  # date to start examine chart patterns
stopDate    <- '2010-12-31'  # date to stop examine chart patterns
maShort     <- 50
maLong      <- 200

matrix(c("2011-05-01", "2011-05-02", "2011-05-03", 11,12,13), nrow=3, ncol=2)
data.frame (c(1,2,3), row.names=c("2011-05-01", "2011-05-02", "2011-05-03"))
xtsf <- xts(fr[,-1], as.Date(fr[,1], origin = "1970-01-01", tz="UTC")+1, src="vadb", updated=Sys.time(), tzone="UTC")


"getSymbols.vadb" <- function(Symbols, env, return.class="xts",
                              datefrom="1970-01-01", dateto=NULL, includeOI=FALSE,
                              user=NULL, password=NULL, dbname=NULL, host=NULL, ...) {
  
  # default settings
  if (is.null(user)) user <- "va"
  if (is.null(password)) password <- "dummy"
  if (is.null(dbname)) dbname <- "va_stratlab"
  if (is.null(host)) host <- "localhost"
  
  importDefaults("getSymbols.vadb")
  this.env <- environment()
  for(var in names(list(...))) {
    assign(var,list(...)[[var]], this.env)
  }
  
  # additional defaults to be saved
  # used if getSymbolLookup has been set
  # for a specific SYMBOL
  
  default.return.class <- return.class
  
  if(missing(verbose)) verbose <- FALSE
  if(missing(auto.assign)) auto.assign <- TRUE
  
  # load DBI and RMySQL packages
  if('package:DBI' %in% search() || require('DBI',quietly=TRUE)) {
    if('package:RMySQL' %in% search() || require('RMySQL',quietly=TRUE)) {
    } else { 
      warning(paste("package:",dQuote("RMySQL"),"cannot be loaded" )) 
    }
  } else {
    stop(paste("package:",dQuote('DBI'),"cannot be loaded."))
  }
  
  if (includeOI==TRUE) {
    oi <- ",oi"
  } else {
    oi <- ""
  }
  # connect to database
  con <- dbConnect(MySQL(), user=user, password=password, dbname=dbname, host=host)
  
  for(i in 1:length(Symbols)) {
    # repeat the following 2 assignments for all default arguments
    return.class <- getSymbolLookup()[[Symbols[[i]]]]$return.class
    return.class <- ifelse(is.null(return.class), default.return.class, return.class)
    
    if(verbose) cat("loading ",Symbols[[i]],".....")
    
    # Build SQL Command
    sql <- sprintf ("SELECT date,open,high,low,close,volume%s 
           FROM stockname LEFT JOIN stockprice ON (id=stock_id) WHERE code='%s'",oi, Symbols[[i]])
    if (!is.null(datefrom)) {
      sql <- paste (sql, sprintf ("AND date>='%s'", datefrom), SEP="")
    }
    if (!is.null(dateto)) {
      sql <- paste (sql, sprintf ("AND date<='%s'", dateto), SEP="")
    }
    # exclude holidays (day without trades)
    sql <- paste (sql,"HAVING !(open=high && high=low && low=close && volume=0)", SEP="")
    sql <- paste (sql,"ORDER BY `date`", SEP="")
    
    if (verbose) cat("sql command:\n",sql,"\n")
    
    fr <- dbGetQuery(con, sql)
    
    # convert to a zoo/xts object. indexing by proper format
    #fr <- zoo(fr[,-1],as.Date(fr[,1],origin='1970-01-01'))
    fr <- xts(fr[,-1], as.Date(fr[,1], origin = "1970-01-01", tz="UTC"), src="vadb", updated=Sys.time(), tzone="UTC" )
    
    # change colnames if necessary.  Following handle OHLC code from yahoo
    if (includeOI==TRUE) {
      colnames(fr) <- paste(toupper(gsub('\\^','',Symbols[[i]])),
                            c('Open','High','Low','Close','Volume','OI'),sep='.')
    } else {
      colnames(fr) <- paste(toupper(gsub('\\^','',Symbols[[i]])),
                            c('Open','High','Low','Close','Volume'),sep='.')      
    }
    
    # convert.time.series to whichever class is specified by 'return.class'
    #fr <- quantmod:::convert.time.series(fr=fr,return.class=return.class)
    
    if(auto.assign)
      assign(Symbols[[i]],fr,env)
    if(verbose)  
      cat("done.\n")
  }
  dbDisconnect(con)
  
  if(auto.assign) return(Symbols)
  return(fr)
}



LagOHLC1 <- function (TS, k = 1) 
{
    if (!is.OHLC(TS)) {
        stop("Price series must contain Open, High, Low and Close.")
    }
    result <- cbind(lag(Op(TS), k), lag(Hi(TS), k), lag(Lo(TS), 
        k), lag(Cl(TS), k))
    colnames(result) <- c(paste(colnames(Op(TS)), k, sep = ".Lag."), 
        paste(colnames(Hi(TS)), k, sep = ".Lag."), paste(colnames(Lo(TS)), 
            k, sep = ".Lag."), paste(colnames(Cl(TS)), k, sep = ".Lag."))
    return(result)
}

findOpportunity2 <- function(TS, n=3) {
  if (!is.OHLC(TS)) {
    stop("Price series must contain Open, High, Low and Close.")
  }
  max <- lag(runMax(Hi(TS),n=n), k=n*(-1))
  min <- lag(runMin(Lo(TS),n=n), k=n*(-1))
  gain <- (max/Cl(TS)-1)*100
  loss <- (min/Cl(TS)-1)*100
  GLR <- (gain-(loss*(-1)))/(gain+(loss*(-1)))
  buyS <- gomperez(GLR)* onlypos(gain)
  buyS <- log(1+ buyS)
  sellS <- gomperez(GLR*(-1))* onlypos(loss*(-1))
  sellS <- log(1+ sellS)
  result <- cbind(max,min,gain,loss,GLR,buyS,sellS)
  colnames(result) <- c("max","min","gain","loss","GLR","buyS","sellS")
  return(cbind (TS,result))  
}

findOpportunity1 <- function(TS, n=3) {
  if (!is.OHLC(TS)) {
    stop("Price series must contain Open, High, Low and Close.")
  }
  max <- lag(runMax(Hi(TS),n=n), k=n*(-1))
  min <- lag(runMin(Lo(TS),n=n), k=n*(-1))
  gain <- (max/Cl(TS)-1)*100
  loss <- (min/Cl(TS)-1)*100
  VSWR <- (gain-(loss*(-1)))/(gain+(loss*(-1)))
  buySignal <- VSWR* onlypos(gain)
  buySignal <- log(1+ onlypos(buySignal))
  sellSignal <- VSWR*(-1)* onlypos(loss*(-1))
  sellSignal <- log(1+ onlypos(sellSignal))
  result <- cbind(max,min,gain,loss,VSWR,buySignal,sellSignal)
  colnames(result) <- c("max","min","gain","loss","VSWR","buyS","sellS")
  return(cbind (TS,result))
}

# retrieve historical data and calculate moving averages
for (symbol in symbols) {
  getSymbols(symbol,from=retrieveDate)
  assign(symbol, adjustOHLC(get(symbol),use.Adjusted=TRUE)) # adjust for splits, dividents
  maS <- SMA(Cl(get(symbol)), n=maShort)     # calculate short SMA
  maL <- SMA(Cl(get(symbol)), n=maLong)      # calculate long SMA
  ClgtmaS <- eval(Cl(get(symbol)) > maS[,1])
  colnames(ClgtmaS) <- c("ClgtmaS")
  ClgtmaL <- eval(Cl(get(symbol)) > maL[,1])
  colnames(ClgtmaL) <- c("ClgtmaL")
  maSRising <- eval(Delt(maS)>0)
  colnames(maSRising) <- c("maSRising")  
  maLRising <- eval(Delt(maL)>0)
  colnames(maLRising) <- c("maLRising")
  symstate <- ClgtmaS[,1]*8 + ClgtmaL[,1]*4 + maSRising[,1]*2 + maLRising[,1]
  colnames(symstate) <- c("state")
  # merge OHLCVA together with SMA's
  assign(symbol, merge(get(symbol),maS,maL,ClgtmaS,ClgtmaL,maSRising,maLRising,symstate))
  EngulfingPattern <- CSPEngulfing(get(symbol))
  assign(symbol, merge(get(symbol),EngulfingPattern))
  
  # cut out the part where indicators have not been calculated
  assign(symbol, get(symbol)[paste(initDate,'::',sep='')])
  
}

head(EngulfingPattern)
head(URZ[,c(1,4,14,15)], n=20)

head(CSPHarami(URZ),n=50)
chartSeries(URZ, subset='first 4 weeks')
